<template>
  <div class="container">
    <h1>✊ ✌️ 🖐 实时识别</h1>

    <!-- 视频展示 -->
    <video ref="video" autoplay playsinline width="640" height="480" v-show="cameraActive" />
    <canvas ref="canvas" width="640" height="480" style="display: none"></canvas>

    <!-- 按钮 -->
    <div style="margin-top: 10px">
      <button @click="startVideo" :disabled="cameraActive">开始识别</button>
      <button @click="stopVideo" :disabled="!cameraActive">结束识别</button>
    </div>

    <!-- 识别结果 -->
    <p v-if="result" class="result-text">
      识别结果：{{ classMap[result.class] || result.class }}（{{ result.confidence.toFixed(1) }}%）
    </p>
    <p v-else-if="cameraActive">识别中...</p>
    <p v-else>点击“开始识别”开启摄像头</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      result: null,
      intervalId: null,
      stream: null,
      cameraActive: false,
      classMap: {
        Rock: '石头',
        Paper: '布',
        Scissors: '剪刀',
      },
    }
  },
  beforeUnmount() {
    this.stopVideo()
  },
  methods: {
    async startVideo() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true })
        this.stream = stream
        this.cameraActive = true
        this.$refs.video.srcObject = stream

        this.intervalId = setInterval(this.captureAndSendFrame, 1000)
      } catch (err) {
        console.error('无法访问摄像头：', err)
      }
    },
    stopVideo() {
      if (this.intervalId) {
        clearInterval(this.intervalId)
        this.intervalId = null
      }
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop())
        this.stream = null
      }
      this.cameraActive = false
      this.result = null
    },
    captureAndSendFrame() {
      const video = this.$refs.video
      const canvas = this.$refs.canvas
      const ctx = canvas.getContext('2d')

      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const dataURL = canvas.toDataURL('image/jpeg')

      fetch('http://localhost:5000/predict_video', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ image: dataURL }),
      })
        .then((res) => res.json())
        .then((data) => {
          if (data.class) {
            this.result = data
          } else {
            this.result = { class: '识别失败', confidence: 0 }
          }
        })
        .catch((err) => {
          console.error('预测请求失败：', err)
        })
    },
  },
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  min-height: 100vh;
  padding-top: 40px;
  box-sizing: border-box;
  text-align: center;
}

video {
  border: 2px solid #ccc;
  border-radius: 8px;
  margin: 10px 0;
  max-width: 100%;
  display: block;
}

button {
  margin: 5px;
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.result-text {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-top: 15px;
}
</style>
